package com.mytime.database;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.mytime.util.Time;

@PersistenceCapable
public class Timetable {
	
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;

	@Persistent
	private String eventId;

	@Persistent
	private String venueId;

	@Persistent
	private int startTime;
	
	@Persistent
	private int endTime;
	
	@Persistent
	private String weekday;

	//*************//
	//Constructors//
	//***********//
	public Timetable() {
		
	}
	
	public Timetable(JSONObject data) {
		try {
			if (data.has("eventId") && data.getString("eventId") != null)
				eventId = data.getString("eventId");
			
			if (data.has("venueId") && data.getString("venueId") != null)
				venueId = data.getString("venueId");
			
			if (data.has("startTime") && data.getString("startTime") != null)
				setStartTime(data.getString("startTime"));
			
			if (data.has("endTime") && data.getString("endTime") != null)
				setEndTime(data.getString("endTime"));
			
			if (data.has("weekday") && data.getString("weekday") != null)
				weekday = data.getString("weekday");
		
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	public String getEventId() {
		return eventId;
	}

	public void setEventId(String eventId) {
		this.eventId = eventId;
	}

	public String getVenueId() {
		return venueId;
	}

	public void setVenueId(String venueId) {
		this.venueId = venueId;
	}

	public int getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = new Time(startTime).getTime();		
	}

	public int getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = new Time(endTime).getTime();
	}

	public String getWeekday() {
		return weekday;
	}

	public void setWeekday(String weekday) {
		this.weekday = weekday;
	}

	public Event getEvent() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Event event = pm.getObjectById(Event.class, this.eventId);
		return event;
	}
	
	public JSONObject toJSON() {
		JSONObject entry = new JSONObject();
		Time startTime = new Time(this.startTime);
		Time endTime = new Time(this.endTime);
		
		try {
			entry.put("startTime", startTime.toString());
			entry.put("endTime", endTime.toString());
			entry.put("weekday", this.weekday);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return entry;
	}
}
